package com.example.weight.wormHandle.cultivate;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.example.weight.util.WeightActivity;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IncubateActivity extends AppCompatActivity {
    private EditText et_material_weight,et_worm_weight,tv_group_number,et_water_weight,remark;
    private TextView tv_start_date, tv_number,tv_index_number;
    private String name, factory;
    private String activeButton = "",material_name="",source_name="";

    Calendar calendar= Calendar.getInstance(Locale.CHINA);

    @SuppressLint("SimpleDateFormat")
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_incubate);

        tv_number = findViewById(R.id.tv_number);
        tv_number.setText("P"+simpleDateFormat2.format(new Date()));

        tv_group_number = findViewById(R.id.tv_group_number);
        tv_index_number = findViewById(R.id.tv_index_number);

//        辅料选择
        RadioGroup material_radioGroup = (RadioGroup)findViewById(R.id.fuliao_group_button);
        material_radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton material_radioButton = (RadioButton)findViewById(material_radioGroup.getCheckedRadioButtonId());
                material_name = material_radioButton.getText().toString();
            }
        });
//        辅料重量
        et_material_weight = findViewById(R.id.et_material_weight);
//        虫卵重量
        et_worm_weight = findViewById(R.id.et_worm_weight);
//        水重量
        et_water_weight = findViewById(R.id.et_water_weight);
        remark = findViewById(R.id.remark);

        tv_start_date = findViewById(R.id.tv_start_date);
        tv_start_date.setText(simpleDateFormat.format(new Date()));
        tv_start_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog(IncubateActivity.this, 2, tv_start_date, calendar);
            }
        });

        TitleBar titleBar = findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                IncubateActivity.this.finish();
            }

            @Override
            public void onTitleClick(View v) {}

            @Override
            public void onRightClick(View v) {}
        });

    Pattern p = Pattern.compile("\\d+");

    RequestQueue queue = Volley.newRequestQueue(this);
    String url = Config.url + "/hsmpy/hatchWorm/getlist" + "?factory=" + factory;
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray data1 = jsonObject.getJSONArray("data");
                        JSONObject data = data1.getJSONObject(0);
                        Log.d("jy", data.toString());
                        if (!data.isNull("id")) {
                            tv_number.setText(data.getString("batch"));
                            tv_group_number.setHint(data.getString("wormGroup"));
                            if(data.getString("fuliaoName").equals("锯末")){//代表锯末
                                material_radioGroup.check(R.id.fuliao1);
                            }else if(data.getString("fuliaoName").equals("麸皮")){//代表麸皮
                                material_radioGroup.check(R.id.fuliao2);
                            }
                            et_material_weight.setHint(data.getString("fuliaoWeight"));
                            et_water_weight.setHint(data.getString("waterWeight"));
                            et_worm_weight.setHint(data.getString("eggWeight"));
                            remark.setHint(data.getString("remark"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(IncubateActivity.this,
                    "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
}


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String weight = data.getStringExtra("weight");
        switch (activeButton){
            case "btn_get_material_weight":
                et_material_weight.setText(weight);
                break;
            case "btn_get_water_weight":
                et_water_weight.setText(weight);
                break;
            case "btn_get_worm_weight":
                et_worm_weight.setText(weight);
                break;
            default:
                break;
        }
    }

    public void goWeight(View view) {
        switch (view.getId()) {
            case R.id.btn_get_material_weight:
                activeButton = "btn_get_material_weight";
                break;
            case R.id.btn_get_water_weight:
                activeButton = "btn_get_water_weight";
                break;
            case R.id.btn_get_worm_weight:
                activeButton = "btn_get_worm_weight";
                break;
            default:
                break;
        }
        Intent intent = new Intent(IncubateActivity.this, WeightActivity.class);
        startActivityForResult(intent, 1);
    }

    public void submit(View view){
        if(tv_start_date.getText().toString().equals("")) {
            Toast.makeText(this, "请填写孵化开始日期", Toast.LENGTH_SHORT).show();
            return;
        }
        if (tv_number.getText().toString().equals("")) {
            Toast.makeText(this, "请填写批次", Toast.LENGTH_SHORT).show();
            return;
        }
        if (tv_group_number.getText().toString().equals("")) {
            Toast.makeText(this, "请填写组别", Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_material_weight.getText().toString().equals("")){
            Toast.makeText(this, "请填写辅料重量", Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_water_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写水重量", Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_worm_weight.getText().toString().equals("")){
            Toast.makeText(this, "请填写虫卵重量", Toast.LENGTH_SHORT).show();
            return;
        }

        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {

                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/hsmpy/hatchWorm/add";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    //Toast.makeText(RepairTable.this, "保存成功", Toast.LENGTH_SHORT).show();
                                    Log.d("jy", response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.startsWith("2")) {
                                            Toast.makeText(IncubateActivity.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
//                                            IncubateActivity.this.finish();
                                        }
                                        else
                                            Toast.makeText(IncubateActivity.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(IncubateActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
                            Log.d("jy", error.toString());
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map = new HashMap<>();
                            map.put("hatch_start_time",tv_start_date.getText().toString());
                            map.put("batch",tv_number.getText().toString());
                            map.put("worm_group", tv_group_number.getText().toString());
                            map.put("fuliao_name", material_name);
                            map.put("fuliao_weight", et_material_weight.getText().toString());
                            map.put("water_weight", et_water_weight.getText().toString());
                            map.put("egg_weight", et_worm_weight.getText().toString());
                            map.put("remark", remark.getText().toString());
                            map.put("factory", factory);
                            Log.d("jy",map.toString());
//                            Log.d("factory",factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }
    public void getIndex(View view){
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/hsmpy/hatchingFeed/getSerial";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        //Toast.makeText(RepairTable.this, "保存成功", Toast.LENGTH_SHORT).show();
                        Log.d("jy", response);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray data = jsonObject.getJSONArray("message");
                            String code = jsonObject.getString("code");
                            if (code.startsWith("2")) {
                                tv_index_number.setText(data.toString());
                            }
                            else
                                Toast.makeText(IncubateActivity.this,
                                        "获取编号失败", Toast.LENGTH_SHORT).show();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(IncubateActivity.this, "获取编号失败", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("batch",tv_number.getText().toString());
                map.put("worm_group", tv_group_number.getText().toString());
                map.put("factory", factory);
                return map;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);

    }

    /**
     * 日期选择
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    public static void showDatePickerDialog(Activity activity, int themeResId, final TextView tv, Calendar calendar) {
        // 直接创建一个DatePickerDialog对话框实例，并将它显示出来
        new DatePickerDialog(activity, themeResId, new DatePickerDialog.OnDateSetListener() {
            // 绑定监听器(How the parent is notified that the date is set.)
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // 此处得到选择的时间，可以进行你想要的操作
                tv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        }
                // 设置初始日期
                , calendar.get(Calendar.YEAR)
                , calendar.get(Calendar.MONTH)
                , calendar.get(Calendar.DAY_OF_MONTH)).show();
    }
}